package redis

import (
	"github.com/gomodule/redigo/redis"
	"log"
	"time"
	"sync"
)

const DeviceName = "proxy" //用来存放设备信息

var (
	c    redis.Conn
	lock sync.RWMutex
)

func Init() {
	c1, err := redis.Dial(
		"tcp",
		"192.168.1.89:6379",
		redis.DialDatabase(10),
		redis.DialPassword("123456"),
	)
	if err != nil {
		log.Fatalln("Connect to redis error" + err.Error())
	} else {
		//c1.Do("select 3")
		c = c1
	}
	//defer c.Close()
}
func init() {
	Init()
}

//添加Proxy
func AddProxy(proxy ...string) (bool, error) {
	lock.Lock()
	reply, err := c.Do("zadd", DeviceName, time.Now().Unix(), proxy)
	lock.Unlock()
	if err != nil {
		log.Println(err)
		Init()
		return false, err
	}
	b, ok := reply.(int64)
	if ok {
		if b >= 1 {
			return true, nil
		} else {
			return false, nil
		}
	} else {
		return false, nil
	}
}

// 根据start和end取proxy
func GetAllProxy(start, end int) []string {
	result := make([]string, 0)
	lock.RLock()
	values, err := redis.Values(c.Do("zrange", DeviceName, start, end))
	lock.RUnlock()
	if err != nil {
		log.Println(err)
		Init()
		return result
	}
	for _, v := range values {
		v2, ok := v.([]byte)
		if ok {
			result = append(result, string(v2))
		} else {
			continue
		}
	}
	return result
}

//删除proxy
func DeleteProxy(proxy string) (bool, error) {
	lock.Lock()
	reply, err := c.Do("zrem", DeviceName, proxy)
	lock.Unlock()
	if err != nil {
		log.Println(err)
		Init()
		return false, err
	}
	b, ok := reply.(int64)
	if ok {
		if b == 1 {
			return true, nil
		} else {
			return false, nil
		}
	} else {
		return false, nil
	}
}
